package org.kongqian.gift.exception.handler;

import org.kongqian.gift.exception.GlobalException;
import org.kongqian.gift.exception.code.ErrorCode;
import org.kongqian.gift.util.AjaxResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

    //能预知的异常
    @ExceptionHandler(GlobalException.class)
    public AjaxResult businessExceptionHandler(GlobalException g){
        g.printStackTrace();
    return AjaxResult.me().setSuccess(false).setMessage(g.getMessage()).setCode(g.getCode());
    }

    //jsr303校验
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException m){
        m.printStackTrace();
        BindingResult bindingResult = m.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        StringBuilder stringBuilder = new StringBuilder();
        fieldErrors.forEach(fieldError -> {
            String message = fieldError.getDefaultMessage();
            stringBuilder.append(message+",");
        });
        String message=stringBuilder.substring(0, stringBuilder.length()-1);
        return AjaxResult.me().setSuccess(false).setMessage(message).setCode(ErrorCode.ERROR_CODE_THE_PARAMETER_IS_INCORRECT.getCode());
    }

    //不能预知的异常
    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage()).setCode(ErrorCode.ERROR_CODE_SYSTEM_EXCEPTION.getCode());
    }
}
